package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import io.jsonwebtoken.lang.Collections;
import lombok.RequiredArgsConstructor;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {
    private final RoleMapper roleMapper;

    /**
     * 分页查询
     */
    @Override
    public PageResponse<RoleVo> pageQuery(int pageNum, int pageSize, RoleDto roleDto) {
        //开启分页
        PageHelper.startPage(pageNum, pageSize);
        // 查询列表
        Page<RoleVo> roleVos = roleMapper.pageQuery(roleDto);
        return PageResponse.of(roleVos,RoleVo.class);
    }

    /**
     * 新增角色
     */
    @Override
    public void addRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.insertRole(role);
    }

    /**
     * 查询角色选中的资源数据
     */
    @Override
    public List<String> queryResourceByRoleId(Long roleId) {
        return  roleMapper.queryResourceByRoleId(Long.valueOf(roleId));
    }

    /**
     * 角色修改
     */
    @Override
    @Transactional
    public void modifyRole(RoleDto roleDto) {
        // 通过id查询角色信息
        Role role=roleMapper.queryById(roleDto.getId());
        if(role == null){
            throw new BaseException(BasicEnum.PARAMETER_MISSING);
        }
        Boolean flag=false;
        //启用禁用
        if(StrUtil.isNotEmpty(roleDto.getDataState()) ){
            if(StrUtil.equals(roleDto.getDataState(), SuperConstant.DATA_STATE_1)){
                //如果用户已经关联角色则不能禁用
                Integer count = roleMapper.queryUserCountByRoleId(roleDto.getId());
                if(count > 0){
                    throw new BaseException(BasicEnum.POSITION_DISTRIBUTED);
                }
            }
            role.setDataState(roleDto.getDataState());
            flag=true;
        }
        //修改角色名称
        if(StrUtil.isNotEmpty(roleDto.getRoleName())){
            role.setRoleName(roleDto.getRoleName());
            flag=true;
        }
        // 修改角色信息
        if(flag){
            roleMapper.modifyRole(role);
        }else {
               if(ArrayUtil.isNotEmpty(roleDto.getCheckedResourceNos())){
                   // 删除旧的角色和资源关联数据
                   roleMapper.deleteByRoleId(roleDto.getId());
                   // 新增新的角色和资源关联数据
                   List<RoleResource> list = Arrays.stream(roleDto.getCheckedResourceNos()).map(resourceNo -> {
                       RoleResource roleResource = new RoleResource();
                       roleResource.setRoleId(roleDto.getId());
                       roleResource.setResourceNo(resourceNo);
                       roleResource.setDataState(SuperConstant.DATA_STATE_0);
                       return roleResource;
                   }).collect(Collectors.toList());
                   // 重新插入角色资源关联数据
                   roleMapper.insertBatch(list);
               }
        }
    }

    /**
     * 删除角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Long roleIds) {
        Role role = roleMapper.queryById(roleIds);
        //1. 如果角色是启用状态 , 不能删除
        if(role.getDataState().equals(SuperConstant.DATA_STATE_0)){
            throw new BaseException(BasicEnum.ENABLED_CANNOT_DELETED);
        }
        //2. 角色被用户引用不能删除
        Integer count = roleMapper.queryUserCountByRoleId(roleIds);
        if(count > 0){
            throw new BaseException(BasicEnum.ROLE_DISTRIBUTED);
        }
        //3. 删除角色数据
        roleMapper.deleteRole(roleIds);
        //4. 删除角色和资源的关联数据
        roleMapper.deleteByRoleId(roleIds);
    }

    /**
     * 角色下拉框
     */
    @Override
    public List<RoleVo> initRoles() {
        List<Role> list= roleMapper.initRoles();
        return BeanUtil.copyToList(list,RoleVo.class);
    }
}
